# python

关于 Python sys.path 包含了奇怪字符串的问题

之前一直不清楚 sys.path 是如何进行初始化的。在我的电脑上,sys.path 输出了以下内容:

['{PWD}',
 '/opt/homebrew/Cellar/python@3.9/3.9.16/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
 '/opt/homebrew/Cellar/python@3.9/3.9.16/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
 '/opt/homebrew/Cellar/python@3.9/3.9.16/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
 '',
 '/Users/user/Library/Python/3.9/lib/python/site-packages',
 '/opt/homebrew/lib/python3.9/site-packages',
 '/opt/homebrew/lib/python3.9/site-packages/potion-0.0.1-py3.9.egg',
 '/opt/homebrew/lib/python3.9/site-packages/pynotion-0.0.1-py3.9.egg',
 '/Users/user/Documents/timeflow/backend_api',
 '/opt/homebrew/lib/python3.9/site-packages/IPython/extensions',
 '/Users/user/.ipython']

这里面有一些不符合常规的路径,包括:

  • 我的项目里的路径
  • 空字符串
  • .ipython

最终找到的来源包括以下途径:

  • 环境变量 $PYTHONPATH
  • /site-packages/*.pth

可以参考 python 官方文档